package 富婆梦.第一阶段.Java基础视频学习.线程的练习.练习.TestNotify;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

/**
 * @ProjectName: java-learning
 * @Package: 富婆梦.第一阶段.线程的练习.练习
 * @ClassName: RunoobTest
 * @Author: hemengjin
 * @Description: 测试notify()方法的使用
 * @Date:2021/10/30 14:07
 * @Version: 1.0
 */
public class RunoobTest {
    private List synchedList;

    public RunoobTest() {
        //创建一个同步列表
        synchedList = Collections.synchronizedList(new LinkedList<>());
    }

    //删除列表中的元素
    public String removeElement() throws InterruptedException {
        synchronized (synchedList) {
            //列表为空就等待
            while (synchedList.isEmpty()) {
                System.out.println(Thread.currentThread().getName()+" List is empty...");
                synchedList.wait();
                System.out.println(Thread.currentThread().getName()+" Waiting...");
            }
            String element = (String) synchedList.remove(0);
            return element;
        }
    }

    //添加元素到列表
    public void addElement(String element){
        System.out.println(Thread.currentThread().getName()+" Opening...");
        synchronized (synchedList){
            //添加一个元素，并通知元素已存在
            synchedList.add(element);
            System.out.println("New Element:'"+element+"'");
            synchedList.notifyAll();
            System.out.println("notifyAll called!");
        }
        System.out.println(Thread.currentThread().getName()+" Closing...");
    }

    public static void main(String[] args) {
        final RunoobTest demo = new RunoobTest();

        //用于移除元素的线程A
        Runnable runA = new Runnable() {
            @Override
            public void run() {
                try{
                    String item = demo.removeElement();
                    System.out.println("删除的元素是："+item);
                }catch (InterruptedException ix){
                    System.out.println("Interrupted Exception");
                }catch (Exception e){
                    System.out.println("Exception throw.");
                }
            }
        };

        //用于添加元素的线程B
        Runnable runB = new Runnable() {
            @Override
            public void run() {
                demo.addElement("Hello!");
            }
        };

        try {
            Thread threadA1 = new Thread(runA,"Google");
            threadA1.start();

            Thread.sleep(500);

            Thread threadA2 = new Thread(runA,"Runoob");
            threadA2.start();

            Thread.sleep(500);

            Thread threadB = new Thread(runB,"Taobao");
            threadB.start();

            Thread.sleep(1000);

            threadA1.interrupt();
            threadA2.interrupt();

        }catch (InterruptedException e){
            e.printStackTrace();
        }

    }
}
